﻿package ua.mihaylenko.cardsplugin.components.cardeditor{
	import fl.data.DataProvider;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.IOErrorEvent;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import fl.transitions.Tween;
	import fl.transitions.easing.Back;
	import fl.controls.UIScrollBar;
	import fl.transitions.easing.Strong;
	import fl.transitions.TweenEvent;
	import fl.events.ScrollEvent;
	import fl.transitions.easing.Bounce;
	import flash.net.URLVariables;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLRequestMethod;
	import flash.events.Event;
	import flash.utils.ByteArray;
	import flash.geom.Rectangle;
	import flash.net.FileReference;
	import ua.mihaylenko.cardsplugin.common.FlashVars;
	import ua.mihaylenko.cardsplugin.components.thumbs.*;
	import ua.mihaylenko.cardsplugin.data.*;
	import com.adobe.images.*;
	import ua.mihaylenko.cardsplugin.utils.StringUtil;
	import flash.external.ExternalInterface;
	import flash.net.navigateToURL;
	import ua.mihaylenko.cardsplugin.utils.ToolTip;
	import ua.mihaylenko.cardsplugin.utils.LocalStorage;
	import ua.mihaylenko.cardsplugin.cardsviwer.Card;
	import ua.mihaylenko.cardsplugin.common.EngineMain;
	import flash.utils.setTimeout;
	import ua.mihaylenko.cardsplugin.common.DocumentClass;
	import flash.ui.Mouse;
	import ua.mihaylenko.cardsplugin.common.FlashVars;

	public class ECEdit extends MovieClip {
		public var _errorMsg:Sprite;
		public var _btnSendContent:SimpleButton;
		public var _smcBG:Sprite;
		public var _smcThumbNovigate:ThumbNovigate;
		public var _UIScrollBar:UIScrollBar;
		public var _smcRightBottom:MovieClip;
		public var _smcMask:Sprite;
		public var _image:Sprite;
		public var _resizing:Sprite;
		private var _smcContent:MovieClip;
		private var _oHide:Object;
		private var _sTemplateID:String;
		private var _twHideShow:Tween;
		private var _URLVariables:URLVariables;
		private var _fLoading:Function;
		private var _fLoaded:Function;
		//private static var _nStageWidth:Number = 555.0;
		private static var pStartContentPosition:Point=new Point(356,12);
		private static const MAILSUBJECT:String="e-card";
		private static const MAILBODY:String="Hi, \nI made a card for you. Click on the link to see it.\n";
		private static var _IMGURL:String="";
		private static var _AccessURL:String="";

		private var _aFilds:Array;
		private var _aImages:Array;

		//ToolTips
		private var _sbtSendTooltip:ToolTip;
		private var _sbtNewWindowTooltip:ToolTip;
		private var _sbtPrintTooltip:ToolTip;
		private var _sbtSaveTooltip:ToolTip;
		private var _sbtEmailTooltip:ToolTip;
		//private var _sbtCloseTooltip:ToolTip;
		private var _imageTooltip:ToolTip;

		//public var _sbtClose:SimpleButton;
		public var _sbtEmail:SimpleButton;
		public var _sbtNewWindow:SimpleButton;
		public var _sbtPrint:SimpleButton;
		public var _sbtSave:SimpleButton;
		public var _sbtEmailIcon:MovieClip;
		public var _sbtNewWindowIcon:MovieClip;
		public var _sbtPrintIcon:MovieClip;
		public var _sbtSaveIcon:MovieClip;

		private var _isLoaded:Boolean=false;

		private var _localSorage:LocalStorage;
		private var _smcLoader:Loader;
		private var _currentH:uint=0;
		private var _currentW:uint=0;
		
		private var _multipageTemplate:Boolean = false;

		public function ECEdit() {
			//trace("tab enabled", this.tabEnabled);
			_smcContent = new MovieClip();
			//_smcContent.tabChildren = true;

			this.addChild(_smcContent);
			_sbtEmail=_smcRightBottom["_sbtEmail"];
			//_sbtClose = _smcRightBottom["_sbtClose"];
			_sbtEmailIcon=_smcRightBottom["_sbtEmailIcon"];
			_sbtNewWindowIcon=_smcRightBottom["_sbtNewWindowIcon"];
			_sbtNewWindow=_smcRightBottom["_sbtNewWindow"];
			
			// add print button
			_sbtPrintIcon=_smcRightBottom["_sbtPrintIcon"];
			_sbtPrint=_smcRightBottom["_sbtPrint"];
			
			_sbtSaveIcon=_smcRightBottom["_sbtSaveIcon"];
			_sbtSave=_smcRightBottom["_sbtSave"];
			_smcThumbNovigate.tabChildren=false;
			_smcThumbNovigate.tabEnabled=false;
			//_sbtClose.tabEnabled = false;
			_sbtEmail.tabEnabled=false;
			_sbtPrint.tabEnabled=false;
			_sbtSave.tabEnabled=false;
			_smcContent.mask=_smcMask;
			//_sbtClose.addEventListener(MouseEvent.CLICK, onCloseMe);
			_btnSendContent.addEventListener(MouseEvent.CLICK, sendContentEventHandler);

			//event handler added to open in new window (by sharwan)
			_sbtNewWindow.addEventListener(MouseEvent.CLICK, imageClickEventHandler);
			
			// register print button event handler
			_sbtPrint.addEventListener(MouseEvent.CLICK, function():void{
			    var _url:String = FlashVars.getInstance().getData("domain") + "/?page=template;TemplateID=" +_sTemplateID;
			    navigateToURL(new URLRequest(_url),"_blank");
			});

			_sbtSave.addEventListener(MouseEvent.CLICK, saveToLocal);
			_sbtEmail.addEventListener(MouseEvent.CLICK, emailClickEventHandler);
			_UIScrollBar.addEventListener(ScrollEvent.SCROLL, onScrollContent);
			_sbtSave.mouseEnabled=false;
			_sbtEmail.mouseEnabled=false;
			//_sbtPrint.mouseEnabled=false;
			this.visible=false;
			_UIScrollBar.visible=false;

			_sbtSendTooltip=new ToolTip("Click to send data.");
			_sbtSendTooltip.attach(_btnSendContent);

			_sbtNewWindowTooltip=new ToolTip("Click to open in new window.");
			_sbtNewWindowTooltip.attach(_sbtNewWindow);

			_sbtPrintTooltip=new ToolTip("Order prints.");
			_sbtPrintTooltip.attach(_sbtPrint);

			_sbtSaveTooltip=new ToolTip("Click to save.");
			_sbtSaveTooltip.attach(_sbtSave);

			_sbtEmailTooltip=new ToolTip("Click to Email this template.");
			_sbtEmailTooltip.attach(_sbtEmail);

			//_sbtCloseTooltip = new ToolTip("Click to see all templates.");
			//_sbtCloseTooltip.attach(_sbtClose);

			_localSorage = new LocalStorage();
			_errorMsg.visible=false;
			_resizing.buttonMode=true;
			_resizing.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
			_resizing.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
			_resizing.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		}
		public function set fLoading(fCaller:Function) {
			_fLoading=fCaller;
		}
		public function set fLoaded(fCaller:Function) {
			_fLoaded=fCaller;
		}

		private function saveToLocal(oEvent:MouseEvent) {
			var cFile:FileReference = new FileReference();
			var cSaveImage:BitmapData;
			for (var i=0; i<_image.numChildren; i++) {
				if (_image.getChildAt(i) is Bitmap) {
					cSaveImage = (_image.getChildAt(i) as Bitmap).bitmapData;
				}
			}
			var oData:ByteArray = new ByteArray();
			oData=PNGEncoder.encode(cSaveImage);
			cFile.save(oData, "card.png");
		}
		private function sendContentEventHandler(event:MouseEvent):void {
			sendAndLoad();
		}
		private function sendAndLoad() {
			_fLoading();
			
			var _url:String = FlashVars.getInstance().getData("domain")+"/?page=template-preview-ecard;TemplateID="+_sTemplateID;
			// append "From=1" to multipage template
			if(this._multipageTemplate){
			    _url = _url + ';From=1';
			}

			var request:URLRequest=new URLRequest(_url);
			request.method=URLRequestMethod.POST;
			for (var i:int = 0; i < _aFilds.length; i++) {
				_URLVariables["_"+_aFilds[i].title]=_aFilds[i].value;
				_localSorage.saveValue(_aFilds[i].title, _aFilds[i].value);
			}

			for (var j:uint = 0; j < _aImages.length; j++) {
				_URLVariables["#"+_aImages[j].title]=ECEImage(_aImages[j]).selectedID;
				if (_aImages[j].selectIndex<0) {
					_localSorage.saveValue(_aImages[j].title, ECEImage(_aImages[j]).cpColor);
				} else {
					var sIndex=ECEImage(_aImages[j]).selectIndex;
					_localSorage.saveValue(_aImages[j].title, ECEImage(_aImages[j]).stockImages[sIndex].id);
				}
			}

			request.data=_URLVariables;

			var _URLLoader:URLLoader = new URLLoader();
			_URLLoader.addEventListener(Event.COMPLETE, imageURLLoaded);
			_URLLoader.load(request);

		}

		private function imageURLLoaded(oEvent:Event) {
			var loader:URLLoader=URLLoader(oEvent.target);
			//var _URLLoader:Loader = new Loader();
			_smcLoader = new Loader();
			_smcLoader.load(new URLRequest(loader.data));
			_IMGURL=loader.data;
			_AccessURL=loader.data;
			_sbtNewWindowIcon.gotoAndStop(2);
			_sbtSaveIcon.gotoAndStop(2);
			if(FlashVars.getInstance().getData("email")) _sbtEmailIcon.gotoAndStop(2);
			_sbtSave.mouseEnabled=true;
			if(FlashVars.getInstance().getData("email")) _sbtEmail.mouseEnabled=true;
			_sbtPrint.mouseEnabled=true;
			//_smcLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
			_smcLoader.contentLoaderInfo.addEventListener(Event.INIT, imageLoaded);
			_smcLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_errorMsg.visible=false;
		}
		private function imageLoaded(oEvent:Event) {
			_smcLoader.contentLoaderInfo.removeEventListener(Event.INIT, imageLoaded);
			_smcLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			var _bmPreview:Bitmap = (oEvent.target.content as Bitmap);
			_bmPreview.smoothing=true;
			var i:int;
			//trace("imageLoaded");
			for (i = 0; i < _image.numChildren; i++) {
				if (_image.getChildAt(i) is Bitmap) {
					/*
					tmpBitmap.x = _image.getChildAt(i).x;
					tmpBitmap.y = _image.getChildAt(i).y;
					tmpBitmap.width = _image.getChildAt(i).width;
					tmpBitmap.height = _image.getChildAt(i).height;
					_image.removeChildAt(i);
					_image.addChild(tmpBitmap);
					*/

					var nPercent:Number=_bmPreview.width/_bmPreview.height;
					var nScaleW:Number=Card._oPictureSettings.width/_bmPreview.width;
					var nScaleH:Number=Card._oPictureSettings.height/_bmPreview.height;
					if (nScaleW<1||nScaleH<1) {
						if (nScaleW<nScaleH) {
							_bmPreview.width*=nScaleW;
							_bmPreview.height=_bmPreview.width/nPercent;
						} else {
							_bmPreview.height*=nScaleH;
							_bmPreview.width=_bmPreview.height*nPercent;
						}
					}
					var nFreeWidth:Number = -(_bmPreview.width - Card._oPictureSettings.width)/2;
					var nFreeHeight:Number = -(_bmPreview.height - Card._oPictureSettings.height)/2;
					if (nFreeWidth>0) {
						nFreeWidth=nFreeWidth;
					} else {
						nFreeWidth=Card._oPictureSettings.x;
					}
					if (nFreeHeight>0) {
						nFreeHeight=nFreeHeight+1;
					} else {
						nFreeHeight=Card._oPictureSettings.y;
					}
					_bmPreview.x=nFreeWidth;
					_bmPreview.y=nFreeHeight;
					_image.removeChildAt(i);
					_image.addChild(_bmPreview);
					break;
				}
			}
			_isLoaded=true;
			_imageTooltip.text="Click to show the preview.";
			_fLoaded();
		}

		//Hanlder IO error to present a friendly error message
		private function ioErrorHandler(event:Event):void {
			_fLoaded();
			_errorMsg.visible=true;
			//_smcPreloader._loaderAnim.gotoAndStop(1);
			//_smcPreloader.visible = false;
		}

		private function onCloseMe(oEvent:MouseEvent) {
			_oHide.Function.apply(_oHide.Object);
		}
		public function set oHide(oHideParam:Object) {
			_oHide=oHideParam;
		}
		private function emailClickEventHandler(event:MouseEvent):void {
			//var mailBody:String=MAILBODY+_IMGURL;

			//var sendMailMSG:String = "mailto:?subject=" + StringUtil.URLEncode(MAILSUBJECT) + "&body=" + StringUtil.URLEncode(mailBody);
			var imgArr:Array = _IMGURL.split("/");
			var sendMailMSG:String = FlashVars.getInstance().getData("email") + imgArr[imgArr.length-1];			
			navigateToURL(new URLRequest(sendMailMSG),"_blank");
			/*
			if (ExternalInterface.available)
			{
			ExternalInterface.call("function( ) { window.location=\""+ sendMailMSG +"\"; }");
			}
			else
			{
			navigateToURL(new URLRequest(sendMailMSG),"_self");
			}
			*/

		}
		public function show(oData:Object=null) {
			_URLVariables = new URLVariables();
			var i:int;
			while (_smcContent.numChildren) {
				_smcContent.removeChildAt(0);
			}
			_smcContent.x=pStartContentPosition.x;
			_smcContent.y=pStartContentPosition.y;
			for (i = 0; i<this.numChildren; i++) {
				if (this.getChildAt(i) is Bitmap) {
					this.removeChildAt(i);
				}
			}
			_aFilds = new Array();
			_aImages = new Array();
			if (oData) {
				_isLoaded=false;
				_IMGURL=oData.url;
				_AccessURL=oData.accessUrl;
				_sbtSave.mouseEnabled=false;
				_sbtEmail.mouseEnabled=false;
				_sbtSaveIcon.gotoAndStop(1);
				_sbtEmailIcon.gotoAndStop(1);
				_URLVariables.Width=oData.image.source.width;
				_URLVariables.Height=oData.image.source.height;
				_sTemplateID=oData.id;
				var tmpBitmap:Bitmap=new Bitmap(oData.image.source,"auto",true);
				tmpBitmap.x=oData.image.x;
				tmpBitmap.y=oData.image.y;
				tmpBitmap.width=oData.image.width;
				tmpBitmap.height=oData.image.height;
				_image.buttonMode=true;
				_imageTooltip=new ToolTip("Click to check the template.");
				_imageTooltip.attach(_image);
				_image.addEventListener(MouseEvent.CLICK, imageClickEventHandler);
				if (_image.numChildren>0) {
					_image.removeChildAt(0);
				}
				_image.addChild(tmpBitmap);
				var backY:int=0;



				for (i = 0; i < oData.filds.length; i++) {
					var cFild:ECEFild = new ECEFild();
					cFild.multiline=oData.filds[i].multiline;
					cFild.title=oData.filds[i].fildName;
					cFild.maxChars=int(Number(oData.filds[i].maxLength));
					cFild.values=oData.filds[i].values;
					if (oData.filds[i].hint) {
						var tmpTooltip:ToolTip=new ToolTip(oData.filds[i].hint);
						tmpTooltip.attach(cFild);
					}
					cFild._stxValue.addEventListener(KeyboardEvent.KEY_DOWN, fildKeyboardEventHandler);
					cFild._stxValue.tabIndex=i+1;
					cFild.value=_localSorage.getValue(oData.filds[i].fildName);
					if (i>0) {
						cFild.y = (_aFilds[i-1].y + _aFilds[i-1].getHeight() + 10);
					}
					cFild.setWidth(_smcMask.width);

					_aFilds.push(_smcContent.addChild(cFild));
				}

				//if there is no textfield, _aFilds will be null, so catched exception
				var nStartImage:Number;
				try {
					nStartImage= (_aFilds[i-1].y + _aFilds[i-1].getHeight() + 10);
				} catch (e) {
				}

				if (oData.images.length) {
					for (i=0; i<oData.images.length; i++) {

						var cImage:ECEImage = new ECEImage();
						cImage.click={Function:choiseImage,Object:this};
						cImage.stockImages=oData.images[i].data;
						cImage.title=oData.images[i].name;



						//added for colorpicker by sharwan
						cImage.colourpicker=oData.images[i].colourpicker;

						//if local storage value matches with stock item id, select it
						//else it may be colour picker value
						var localSValue=_localSorage.getValue(oData.images[i].name);
						var stockFlag=false;
						//find if this stockitem exists
						for (var k=0; k<cImage.stockImages.length; k++) {
							if (cImage.stockImages[k].id==localSValue) {
								cImage.selectIndex=k;
								stockFlag=true;
								break;
							}
						}
						if (stockFlag==false) {
							//check if its valid color value
							var myPattern:RegExp=/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})/gi;
							if (localSValue.match(myPattern)) {
								cImage.cpColor=localSValue;
							}
						}

						cImage.tabEnabled=false;
						cImage.tabChildren=false;
						//cImage.tabIndex = _aFilds.length + i;
						if (i>0) {
							cImage.y = (_aImages[i-1].y + 25);
						} else {
							cImage.y=nStartImage;
						}
						_aImages.push(_smcContent.addChild(cImage));
					}
				}

				if (_aImages.length) {
					_smcThumbNovigate.visible=true;
					this.setChildIndex(_smcThumbNovigate, this.numChildren-1);
					
					// disable default selection.
					//choiseImage(_aImages[0]);
				} else {
					_smcThumbNovigate.visible=false;
				}
				if ((_smcContent.height - _smcMask.height) > 1) {
					_UIScrollBar.visible=true;
					_UIScrollBar.setScrollProperties(_smcContent.height,0 , (_smcContent.height - _smcMask.height) );
				} else {
					_UIScrollBar.visible=false;
				}
			}

			if (_twHideShow) {
				_twHideShow.stop();
				if (_twHideShow.hasEventListener(TweenEvent.MOTION_FINISH)) {
					_twHideShow.removeEventListener(TweenEvent.MOTION_FINISH, close);
				}
			}
			_btnSendContent.tabIndex=_aFilds.length+1;
			this.visible=true;
			_twHideShow=new Tween(this,"alpha",Strong.easeInOut,0,1,30,false);
			//_twHideShow = new Tween(this, "x", Back.easeInOut, -_nStageWidth, 0, 30, false);
			
			// show or hide "print" button according the "download" attribute
			var _showPrint:Boolean = true;
			if(oData.download != null && oData.download == 'only'){
			    _showPrint = false;
			}
			
			this._sbtPrint.visible = _showPrint;
			this._sbtPrintIcon.visible = _showPrint;
			this._sbtNewWindow.visible = !_showPrint;
			this._sbtNewWindowIcon.visible = !_showPrint;
			
			this._multipageTemplate = oData.multipage;
		}
		private function onScrollContent(oEvent:ScrollEvent) {
			_smcContent.y=pStartContentPosition.y-oEvent.position;
		}
		private function choiseImage(cImage:ECEImage) {
			for (var i:int = 0; i < _aImages.length; i++) {
				if (! _aImages[i]==cImage) {
					_aImages[i].selected=false;
				}
			}
			if (! cImage.selected) {
				cImage.selected=true;
				_smcThumbNovigate.onInitialaze(cImage.stockImages, cImage);
				_smcThumbNovigate.showSelectedItem();
				
				if(FlashVars.getInstance().isSingleTemplate()){
				    EngineMain.instance._embedPanel.visible = false;
				    _smcThumbNovigate.show();
				}
				
				// var tabData:Array=["Designs","Embed","Stock images"];
				var tabData:Array = this.generateTabData();
				EngineMain.instance._tabBar.dataProvider=new DataProvider(tabData);
				
				// move it out of "if" to open the tab at any click
				// setTimeout(function():void { EngineMain.instance._tabBar.selectedIndex = 2; }, 50);
				
				//_smcThumbNovigate.addListener(MouseEvent.CLICK, {_function:onThumbClick, _object:this});
			}
			
			setTimeout(function():void { 
			    if(FlashVars.getInstance().isSingleTemplate()){
				    EngineMain.instance._tabBar.selectedIndex = 1; 
				}else{
				    EngineMain.instance._tabBar.selectedIndex = 2; 
				    }
				}, 50);
		}
		public function hide() {
			_twHideShow.stop();
			//_twHideShow = new Tween(this, "x", Back.easeInOut, 0, -_nStageWidth, 30, false);
			_twHideShow=new Tween(this,"alpha",Strong.easeInOut,1,0,30,false);
			_twHideShow.addEventListener(TweenEvent.MOTION_FINISH, close);
		}
		private function close(oEvent:TweenEvent) {
			this.visible=false;
			_twHideShow.removeEventListener(TweenEvent.MOTION_FINISH, close);
		}

		private function fildKeyboardEventHandler(event:KeyboardEvent):void {
			var code:Number=KeyboardEvent(event).keyCode;
			var field:ECEFild=ECEFild(event.target.parent);
			if ((code == Keyboard.ENTER) && !field.multiline) {
				sendAndLoad();
			}
		}

		private function onThumbClick(oEvent:DataThumb):void {
			trace(oEvent.thumb);
		}

		// print button action
		private function printClickEventHandler(event:MouseEvent):void{
		    trace('print');
		}
		
		private function imageClickEventHandler(event:MouseEvent):void {
			navigateToURL(new URLRequest(_AccessURL),"_blank");
		}

		public function mouseOverHandler(event:MouseEvent):void {
			Mouse.hide();
			_resizing.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			DocumentClass.AppStage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
		}

		private function mouseMoveHandler(event:MouseEvent):void {
			EngineMain.instance._cursor.x=event.stageX;
			EngineMain.instance._cursor.y=event.stageY;
			event.updateAfterEvent();
			EngineMain.instance._cursor.visible=true;
			_smcBG.x=_resizing.x+7;
			_smcBG.width=DocumentClass.AppStage.stageWidth-_smcBG.x;
			_btnSendContent.x=_smcBG.x+6;
			_smcRightBottom.x=DocumentClass.AppStage.stageWidth-127;
			if (_smcBG.width<120) {
				_smcRightBottom.visible=false;
			} else {
				_smcRightBottom.visible=true;
			}
			_smcMask.x=_smcBG.x+7;
			_smcMask.width=_smcBG.width-28;
			pStartContentPosition.x=_smcMask.x+7;
			_UIScrollBar.x=DocumentClass.AppStage.stageWidth-20;
			_smcContent.x=pStartContentPosition.x;
			for (var i:uint = 0; i < _smcContent.numChildren; i++) {
				var cfild:ECEFild;
				if (_smcContent.getChildAt(i) is ECEFild) {
					cfild=_smcContent.getChildAt(i) as ECEFild;
					cfild.setWidth(_smcMask.width);
				}
			}
		}

		public function mouseOutHandler(event:MouseEvent):void {
			Mouse.show();
			_resizing.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			EngineMain.instance._cursor.visible=false;
		}
		private function mouseLeaveHandler(event:Event):void {
			mouseMoveHandler(new MouseEvent(MouseEvent.MOUSE_MOVE));
			mouseOutHandler(new MouseEvent(MouseEvent.MOUSE_MOVE));
			DocumentClass.AppStage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
		}

		private function mouseDownHandler(event:MouseEvent):void {
			_resizing.startDrag(false, new Rectangle( 0, 0, DocumentClass.AppStage.stageWidth - 10, 0));
			DocumentClass.AppStage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		}

		private function mouseUpHandler(event:MouseEvent):void {
			_resizing.stopDrag();
			mouseMoveHandler(new MouseEvent(MouseEvent.MOUSE_MOVE));
			DocumentClass.AppStage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			Card.instance._smcRight.width=_smcBG.width;
			Card.instance._smcRight.x=_smcBG.x;
			Card._oPictureSettings.width=DocumentClass.AppStage.stageWidth-_smcBG.width;
			Card._oPictureSettings.height=_smcBG.height;
			Card.instance.calculateWH();
			Card.instance._smcPreloader.x = (DocumentClass.AppStage.stageWidth - Card.instance._smcRight.width) / 2;
			Card.instance._sdtDescription.x=_smcBG.x+8;
			Card.instance._sdtDescription.width=_smcBG.width-15;
			//EngineMain.instance._smcLoading._smcLoadingBar.x = (DocumentClass.AppStage.stageWidth - EngineMain.instance._smcCard._smcRight.width) / 2;
			reloadImage();
		}

		private function resizedImageUrl():String {
			_currentH=Card._currentH;
			_currentW=Card._currentW;
			return StringUtil.replace(_IMGURL, ".jpg", "_"+Card._currentW.toString()+"x"+Card._currentH.toString()+".jpg");
		}

		public function resize(width:int, height:int):void {
			_errorMsg.x = (width - _smcRightBottom.width - _errorMsg.width/2) / 2;
			_errorMsg.y = (height - _smcRightBottom.height) / 2;
			//_smcRightBottom.x = width - _smcRightBottom.width - 3;
			//_smcRightBottom.y = height - _smcRightBottom.height - 3;
			//_smcThumbNovigate.x = (width - 540) / 2;
			_smcThumbNovigate.y=height-60;
			_smcThumbNovigate.resize(width - 60);

			_smcBG.x=width-_smcBG.width;
			_smcBG.height=height-68;
			_resizing.x=_smcBG.x-7;
			_resizing.height=height-68;
			_btnSendContent.x=_smcBG.x+6;
			_btnSendContent.y=_smcBG.height-29;
			_smcRightBottom.x=width-127;
			_smcRightBottom.y=_btnSendContent.y;

			_smcMask.x=_smcBG.x+7;
			_smcMask.height=_smcBG.height-45;

			pStartContentPosition.x=_smcMask.x+7;
			_UIScrollBar.x=width-20;
			_UIScrollBar.height=_smcMask.height;
			_smcContent.x=pStartContentPosition.x;
			if ((_smcContent.height - _smcMask.height) > 1) {
				_UIScrollBar.visible=true;
				_UIScrollBar.setScrollProperties(_smcContent.height,0 , (_smcContent.height - _smcMask.height) );
			} else {
				_UIScrollBar.visible=false;
			}
			reloadImage();
		}

		public function reloadImage():void {
			if (_currentH==Card._currentH&&_currentW==Card._currentW) {
				return;
			}
			if (this.visible&&_image.numChildren) {
				/*
				var _bmPreview:Bitmap = Bitmap(_image.getChildAt(0));
				var nPercent:Number = _bmPreview.width/_bmPreview.height;
				var nScaleW:Number = Card._oPictureSettings.width/_bmPreview.width;
				var nScaleH:Number = Card._oPictureSettings.height/_bmPreview.height;
				if (nScaleW < 1 || nScaleH < 1)
				{
				if(nScaleW<nScaleH){
				_bmPreview.width *= nScaleW;
				_bmPreview.height = _bmPreview.width / nPercent;
				}else{
				_bmPreview.height *= nScaleH;
				_bmPreview.width = _bmPreview.height * nPercent;
				}
				}
				var nFreeWidth:Number = -(_bmPreview.width - Card._oPictureSettings.width)/2;
				var nFreeHeight:Number = -(_bmPreview.height - Card._oPictureSettings.height)/2;
				if(nFreeWidth>0)nFreeWidth = nFreeWidth; else nFreeWidth = Card._oPictureSettings.x;
				if(nFreeHeight>0)nFreeHeight = nFreeHeight+1;else nFreeHeight = Card._oPictureSettings.y;
				_bmPreview.x = nFreeWidth;
				_bmPreview.y = nFreeHeight;
				*/
				//if ( _isLoaded )
				//{
				//trace(resizedImageUrl());
				//var _URLLoader:Loader = new Loader();
				//_URLLoader.load(new URLRequest(resizedImageUrl()));
				//_URLLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
				//_smcLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
				if (_smcLoader==null) {
					_smcLoader = new Loader();
				}
				_smcLoader.contentLoaderInfo.addEventListener(Event.INIT, imageLoaded);
				_smcLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				//trace(_sImage);
				//_250x500
				//trace(resizedImageUrl());
				try {
					//_smcLoader.close();
					_smcLoader.load(new URLRequest(resizedImageUrl()));
					_errorMsg.visible=false;
				} catch (e:Error) {
					//trace("badURL")
				}
				//}
			}
		}
		
		// generate tabs according to the view mode.
		private function generateTabData():Array{
		    if(FlashVars.getInstance().isSingleTemplate()){
			    return ["Embed","Stock images"];
			}else{
			    return ["Designs","Embed","Stock images"];
			}
		}
	}
}